<!--
 * @Descripttion: 大二一名学习前端开发的计科学生，缓慢成长中！
 * @emial: 2392862431@qq.com
 * @Author: SummerSofts
 * @Date: 2023-08-09 09:36:12
 * @LastEditors: SummerSofts
 * @LastEditTime: 2023-09-11 22:23:34
-->
<template>
    <div class="previewBox">
        <pre v-if="showCode" v-highlight>
            <img id="copy_text" :data-clipboard-text="sourceCode" @click="handleCopy" src="../assets/icon/copy.png" alt="">
        <code class="codeBox">{{ sourceCode }}</code>
        </pre>
        <div class="op" @click.stop="showCode = !showCode">{{showCode==false?"查看使用源码":"隐藏源码"}}</div>

    </div>
</template>


<script setup>
import Clipboard from "clipboard";
import { ref, reactive, onMounted} from "vue"
import { useRoute, useRouter } from "vue-router"
const props = defineProps({
   cptName: {
        type: String,
        required: true
    },
    demoName: {
        type: String,
        required: true
    }
})

let showCode = ref(false)
const border = ref("1px solid rgba(0,0,0,.06)")
const showOrhideCode = () => {
    showCode.valueOf = !showCode.value
    if (showCode.value) {
        border.value = "0"
    }
    else {
        border.value = "1px solid rgba(0,0,0,.06)"
    }
}
const sourceCode = ref("")
async function getSourceCode() {
    const isDev = import.meta.env.MODE === "development"
    if (isDev) {
        sourceCode.value = (
            await import(
                `../components/${props.cptName}/demo/${props.demoName}.vue?raw`
            )
        ).default
    }
    else {
        sourceCode.value = await fetch(
            `../components/${props.cptName}/demo/${props.demoName}.vue`
        ).then(res => res.text())
    }
}
const handleCopy = () => {
    let clipboard = new Clipboard("#copy_text");
    clipboard.on("success", (e) => {
        alert("复制成功！")
        clipboard.destroy(); // 释放内存
    });
    clipboard.on("error", (e) => {
        // 不支持复制
        alert("复制失败，不支持！")
        clipboard.destroy(); // 释放内存
    });

}
onMounted(() => {
    getSourceCode()
})

</script>


<style lang="less" scoped>
#copy_text{
    position: absolute;
    width:30px;
    height: 30px;
    right:10px;
    top:10px;
    cursor: pointer;
}
.previewBox{
    width: 70%;
    position: relative;
    height: auto;
    margin: 5px 0;
    background-color: rgb(246, 245, 245);
    border-radius: 20px;
    pre{
        background-color: rgb(9, 9, 9);
        color: white;
    }
    .op{
        width:20%;
        height: 3vh;
        font-family: 'Yomogi';
        line-height: 3vh;
        margin-bottom: 14px;
        text-align: center;
        margin: 4px auto;
        cursor: pointer;
    }
    .op:hover{
        color: skyblue;
    }
}
</style>
